package com.netsdk.demo.customize;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.netsdk.lib.enumeration.EM_DETECT_SENSOR_TYPE;
import com.netsdk.lib.enumeration.EM_TRAFFIC_FLOW_STATUS;
import com.netsdk.lib.enumeration.EM_VEHICLEINOUT_CAR_TYPE;
import com.netsdk.lib.enumeration.EM_VIRTUAL_COIL_OCCUPANCY_STATUS;
import com.netsdk.lib.structure.ALARM_VEHICLE_INOUT_INFO;
import com.netsdk.lib.structure.NET_VEHICLE_OBJECT;
import com.sun.jna.Memory;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import static com.netsdk.lib.Utils.getOsPrefix;

/**
 * @author 291189
 * @version 1.0
 * @description
 * @date 2023/4/11 14:22
 */
public class VehicleInoutDemo {
    // SDk对象初始化
    public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
    public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

    // 判断是否初始化
    private static boolean bInit = false;
    // 判断log是否打开
    private static boolean bLogOpen = false;
    // 设备信息
    private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
    // 登录句柄
    private NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);


    // 回调函数需要是静态的，防止被系统回收
    // 断线回调
    private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
    // 重连回调
    private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

    // 报警事件订阅函数
    private final NetSDKLib.fMessCallBackEx1 messageCallBack = MessCallBack.getSingleInstance();

    // 编码格式
    public static String encode;

    static {
        String osPrefix = getOsPrefix();
        if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
            encode = "GBK";
        } else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
            encode = "UTF-8";
        }
    }

    /**
     * 获取当前时间
     */
    public static String GetDate() {
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
    }

    /**
     * 初始化SDK库
     */
    public static boolean Init() {
        bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
        if (!bInit) {
            System.out.println("Initialize SDK failed");
            return false;
        }
        // 配置日志
        VehicleInoutDemo.enableLog();

        // 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
        netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

        // 设置登录超时时间和尝试次数，可选
        // 登录请求响应超时时间设置为3S
        int waitTime = 3000;
        // 登录时尝试建立链接 1 次
        int tryTimes = 1;
        netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
        // 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
        // 接口设置的登录设备超时时间和尝试次数意义相同,可选
        NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
        // 登录时尝试建立链接的超时时间
        netParam.nConnectTime = 10000;
        // 设置子连接的超时时间
        netParam.nGetConnInfoTime = 3000;
        netsdk.CLIENT_SetNetworkParam(netParam);
        return true;
    }

    /**
     * 打开 sdk log
     */
    private static void enableLog() {
        NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
        File path = new File("sdklog/");
        if (!path.exists())
            path.mkdir();

        // 这里的log保存地址依据实际情况自己调整
        String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
        setLog.nPrintStrategy = 0;
        setLog.bSetFilePath = 1;
        System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
        System.out.println(logPath);
        setLog.bSetPrintStrategy = 1;
        bLogOpen = netsdk.CLIENT_LogOpen(setLog);
        if (!bLogOpen)
            System.err.println("Failed to open NetSDK log");
    }

    /**
     * 高安全登录
     */
    public void loginWithHighLevel() {
        // 输入结构体参数
        NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
            {
                szIP = m_strIpAddr.getBytes();
                nPort = m_nPort;
                szUserName = m_strUser.getBytes();
                szPassword = m_strPassword.getBytes();
            }
        };
        // 输出结构体参数
        NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

        // 写入sdk
        m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
        if (m_hLoginHandle.longValue() == 0) {
            System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
                    netsdk.CLIENT_GetLastError());
        } else {
            deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
            System.out.println("Login Success");
            System.out.println("Device Address：" + m_strIpAddr);
            System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
        }
    }

    /**
     * 退出
     */
    public void logOut() {
        if (m_hLoginHandle.longValue() != 0) {
            netsdk.CLIENT_Logout(m_hLoginHandle);
            System.out.println("LogOut Success");
        }
    }

    /**
     * 清理sdk环境并退出
     */
    public static void cleanAndExit() {
        if (bLogOpen) {
            netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
        }
        netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
        System.exit(0);
    }


    public static Pointer GetStringToPointer(String src, String charset) {
        Pointer pointer = null;
        try {
            byte[] b = src.getBytes(charset);

            pointer = new Memory(b.length + 1);
            pointer.clear(b.length + 1);

            pointer.write(0, b, 0, b.length);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return pointer;
    }

    public static class MessCallBack implements NetSDKLib.fMessCallBackEx1 {


        private static MessCallBack singleInstance=new MessCallBack();;

        public static MessCallBack getSingleInstance() {

            return singleInstance ;
        }


        // bAlarmAckFlag : TRUE,该事件为可以进行确认的事件；FALSE,该事件无法进行确认
        // nEventID 用于对 CLIENT_AlarmAck 接口的入参进行赋值,当 bAlarmAckFlag 为 TRUE 时,该数据有效
        // pBuf内存由SDK内部申请释放
        @Override
        public boolean invoke(int lCommand,                 // 事件枚举 配合 pStuEvent dwBufLen 可以获取事件信息
                              NetSDKLib.LLong lLoginID,     // 登录句柄
                              Pointer pStuEvent,            // 事件信息指针
                              int dwBufLen,                 // 事件信息长度
                              String strDeviceIP,           // 设备IP
                              NativeLong nDevicePort,       // 设备TCP端口
                              int bAlarmAckFlag, NativeLong nEventID, Pointer dwUser) {
            try {
                switch (lCommand) {
                    case NetSDKLib.NET_ALARM_VEHICLE_INOUT: {   // 车辆出入事件 vehicleInOut

                        ParsingVehicleInOut(pStuEvent);
                        break;
                    }
                    default:
                        System.out.printf("Get Other Event 0x%x\n", lCommand);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
    }


    // 车辆进出车道报警 vehicleInOut
    public static void ParsingVehicleInOut(Pointer pStuEvent) throws UnsupportedEncodingException {
        System.out.println("\n\n<Alarm Event> [ ALARM VEHICLE INOUT 车辆出入事件 ]");

        ////////////////////////////// <<-----获取事件信息----->> //////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////

        ALARM_VEHICLE_INOUT_INFO stuAlarmInfo = new ALARM_VEHICLE_INOUT_INFO();
        ToolKits.GetPointerDataToStruct(pStuEvent, 0, stuAlarmInfo);

        int nAction = stuAlarmInfo.nAction;                         // 事件动作,0表示脉冲事件
        int nChannelID = stuAlarmInfo.nChannel;                     // 通道号
        String szName = new String(stuAlarmInfo.szName, encode);    // 事件名称
        String UTC = stuAlarmInfo.UTC.toStringTime();               // 事件发生的时间
        int nEventID = stuAlarmInfo.nEventID;

        int nObjectNum = stuAlarmInfo.nObjectNum;   // 有效物体个数
        NET_VEHICLE_OBJECT[] stObjects = new NET_VEHICLE_OBJECT[nObjectNum];
        for (int i = 0; i < nObjectNum; i++) {
            stObjects[i] = new NET_VEHICLE_OBJECT();
        }
        ToolKits.GetPointerDataToStructArr(stuAlarmInfo.pstObjets, stObjects);

        int nStatNum = stuAlarmInfo.nStatNum;       // 统计有效个数

        // 打印出来看一下
        StringBuilder info = new StringBuilder()
                .append("nAction 事件状态 0->脉冲: ").append(nAction).append("\n")
                .append("nChannelID 通道号 : ").append(nChannelID).append("\n")
                .append("szName 事件名称: ").append(szName).append("\n")
                .append("UTC 发生时间: ").append(UTC).append("\n")
                .append("nEventID 事件ID: ").append(nEventID).append("\n");
        info.append("////// 有效物体个数: ").append(nObjectNum).append("\n");
        for (int i = 0; i < nObjectNum; i++) {
            info.append("// --> 物体序号: ").append(i).append("\n")
                    .append("   nObjectID 物体ID:").append(stObjects[i].nObjectID).append("\n")
                    .append("   nSpeed 车速，单位km/h:").append(stObjects[i].nSpeed).append("\n")
                    .append("   szObjectType 物体类型:").append(new String(stObjects[i].szObjectType, encode)).append("\n")
                    .append("   emSubObject 物体子类别(NetSDKLib.EM_CATEGORY_TYPE):").append(stObjects[i].emSubObject).append("\n")
                    .append("   nLane 物理车道号:").append(stObjects[i].nLane).append("\n")
                    .append("   nRoadwayNumber 自定义车道号:").append(stObjects[i].nRoadwayNumber).append("\n")
                    .append("   emSensorType 传感器类型:").append(EM_DETECT_SENSOR_TYPE.getEnum(stObjects[i].emSensorType).getNote()).append("\n")
                    .append("   nObjectRVID 物体雷达和视频融合ID:").append(stObjects[i].nObjectRVID).append("\n")
                    .append("   nObjectRID 物体的雷达ID:").append(stObjects[i].nObjectRID).append("\n")
                    .append("   szDrivingDirection[0] 行驶方向:").append(new String(stObjects[i].szDrivingDirection[0].info, encode)).append("\n")
                    .append("   szDrivingDirection[1] 上行地点:").append(new String(stObjects[i].szDrivingDirection[1].info, encode)).append("\n")
                    .append("   szDrivingDirection[2] 下行地点:").append(new String(stObjects[i].szDrivingDirection[2].info, encode)).append("\n")
                    .append("   szPlateNumber 车牌号码:").append(new String(stObjects[i].szPlateNumber, encode)).append("\n")
                    .append("   szPlateColor 车牌颜色:").append(new String(stObjects[i].szPlateColor, encode)).append("\n")
                    .append("   dbLongitude 车辆经度:").append(stObjects[i].dbLongitude).append("\n")
                    .append("   dbLatitude 车辆纬度:").append(stObjects[i].dbLatitude).append("\n")
                    .append("   szCarColor 车身颜色:").append(new String(stObjects[i].szCarColor, encode)).append("\n")
                    .append("   emCarType 车辆类型:").append(EM_VEHICLEINOUT_CAR_TYPE.getEnum(stObjects[i].emCarType).getNote()).append("\n")
                    .append("   emVirtualCoilDirection 车辆驶入驶出状态(NetSDKLib.NET_FLOWSTAT_DIRECTION):").append(stObjects[i].emVirtualCoilDirection).append("\n")
                    .append("   dbDistanceToStop 距离停车线距离:").append(stObjects[i].dbDistanceToStop).append("\n")
                    .append("   dbCarX 车道的中心点 X轴方向:").append(stObjects[i].dbCarX).append("\n")
                    .append("   dbCarY 车道的中心点 Y轴方向:").append(stObjects[i].dbCarY).append("\n")

                    .append("   nObjectInVideoLane 物体是否在视频车道内:").append(stObjects[i].nObjectInVideoLane).append("\n")

                    .append("   nDirection 目标物体实际行驶方向:").append(stObjects[i].nDirection).append("\n")

                    .append("   fSpeedX 目标横向运动速度:").append(stObjects[i].fSpeedX).append("\n")

                    .append("   fSpeedY 目标纵向运动速度:").append(stObjects[i].fSpeedY).append("\n")

                    .append("   dbHeadingAngle 航向角:").append(stObjects[i].dbHeadingAngle).append("\n")

                    .append("   stuCarBoundingBox 车身坐标:").append(stObjects[i].stuCarBoundingBox.toString()).append("\n");
        }
        info.append("////// 统计有效个数: ").append(nStatNum).append("\n");
        for (int i = 0; i < nStatNum; i++) {
            info.append("// --> 统计序号: ").append(i).append("\n")
                    .append("   nLane 物理车道号:").append(stuAlarmInfo.stuStats[i].nLane).append("\n")
                    .append("   nRoadwayNumber 自定义车道号:").append(stuAlarmInfo.stuStats[i].nRoadwayNumber).append("\n")
                    .append("   emStatus 流量状态:").append(EM_TRAFFIC_FLOW_STATUS.getEnum(stuAlarmInfo.stuStats[i].emStatus).getNote()).append("\n")
                    .append("   emHeadCoil 车头虚拟线圈状态:").append(EM_VIRTUAL_COIL_OCCUPANCY_STATUS.getEnum(stuAlarmInfo.stuStats[i].emHeadCoil).getNote()).append("\n")
                    .append("   emTailCoil 车尾虚拟线圈状态:").append(EM_VIRTUAL_COIL_OCCUPANCY_STATUS.getEnum(stuAlarmInfo.stuStats[i].emTailCoil).getNote()).append("\n")
                    .append("   nSpeed 车道平均速度(单位：km/h):").append(stuAlarmInfo.stuStats[i].nSpeed).append("\n")
                    .append("   nQueueLen 排队长度(单位：cm):").append(stuAlarmInfo.stuStats[i].nQueueLen).append("\n")
                    .append("   nCarsInQueue 排队车辆数:").append(stuAlarmInfo.stuStats[i].nCarsInQueue).append("\n")
                    .append("   emSensorType 传感器类型 :").append(EM_DETECT_SENSOR_TYPE.getEnum(stuAlarmInfo.stuStats[i].emSensorType).getNote()).append("\n")
                    .append("   dbSpaceOccRatio 空间占有率 :").append(stuAlarmInfo.stuStats[i].dbSpaceOccRatio).append("\n")
                    .append("   nCarVehicles 车流量 :").append(stuAlarmInfo.stuStats[i].nCarVehicles).append("\n");
        }
        System.out.println(info.toString());
    }
    public void RunTest()
    {
        System.out.println("Run Test");
        CaseMenu menu = new CaseMenu();;
        menu.addItem(new CaseMenu.Item(this, "订阅报警事件任务(StartListen)", "AttachEventStartListen"));
        menu.addItem(new CaseMenu.Item(this, "退订报警事件任务(StopListen)", "DetachEventStopListen"));
        menu.run();
    }
    // 配置登陆地址，端口，用户名，密码
    private String m_strIpAddr = "10.33.121.58";
    private int m_nPort = 37777;
    private String m_strUser = "admin";
    private String m_strPassword = "admin";
    public static void main(String[] args) {
        VehicleInoutDemo demo=new VehicleInoutDemo();
        demo.InitTest();
        demo.RunTest();
        demo.EndTest();

    }
    /**
     * 订阅一般报警事件
     */
    public void AttachEventStartListen() {

        // 一般报警不需要指定通道，自动全通道订阅
        boolean bRet = netsdk.CLIENT_StartListenEx(m_hLoginHandle);
        if (bRet) {
            System.out.println("CLIENT_StartListenEx Succeed.");
        } else {
            System.err.printf("CLIENT_StartListenEx fail, error:%s\n", ToolKits.getErrorCode());
        }
    }

    /**
     * 退订一般报警事件
     */
    public void DetachEventStopListen() {
        boolean bRet = netsdk.CLIENT_StopListen(m_hLoginHandle);
        if (bRet) {
            System.out.println("CLIENT_StopListen succeed");
        } else {
            System.err.printf("CLIENT_StopListen fail, error:%s\n", ToolKits.getErrorCode());
        }
    }

    /**
     * 初始化测试
     */
    public void InitTest() {
        VehicleInoutDemo.Init();

        // 注册报警一般事件回调函数 回调函数必须保证不被JVM回收 推荐写成静态单例 dwUser可以不填 也不推荐使用
        // 事件订阅时需要传登录句柄 回调函数会回传获该句柄 回调的数据还会包含通道 可以依据这两者建立事件和设备、通道的映射关系
        netsdk.CLIENT_SetDVRMessCallBackEx1(messageCallBack, null);

        this.loginWithHighLevel();
    }

    /**
     * 结束测试
     */
    public void EndTest() {
        System.out.println("End Test");
        this.logOut(); // 登出设备
        System.out.println("See You...");
        VehicleInoutDemo.cleanAndExit(); // 清理资源并退出
    }

}
